//
//  SsehInvoiceTitleViewController.m
//  customer
//
//  Created by 杨阳 on 2018/11/1.
//  Copyright © 2018 yinlong. All rights reserved.
//

#import "SsehInvoiceTitleViewController.h"
#import "SsehMJFooterTool.h"
#import "SsehMJHeaderTool.h"
#import "MJRefresh.h"
#import "NodataView.h"
#import "SsehAddInvoiceTitleViewController.h"
#import "SsehInvoiceTitleTableViewCell.h"
#import "SsehInvoiceTitleEditViewController.h"
#import "ChargeInvoicePersionalViewController.h"
#import "ChargeInvoiceCompanyViewController.h"

@interface SsehInvoiceTitleViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * ssehTableView;

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (nonatomic,strong) NodataView * noDataView;

@end

static NSString * const SsehInvoiceTitleTableViewCellID = @"SsehInvoiceTitleTableViewCellID";

static int pageIndex = 1;

@implementation SsehInvoiceTitleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseSetting];
    [self creatRefreshHeader];
    [self creatRefreshAutoNormalFooter];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.ssehTableView.mj_header beginRefreshing];
}

-(void)baseSetting{
    if (self.comeIndex == 1) {
        self.title = @"选择抬头";
    }else{
       self.title = @"发票管理";
    }
    UIButton * rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, NAVIGATION_BAR_HEIGHT)];
    UIImage * buttonImage = [UIImage imageNamed:@"addressManagerAdd"];
    [rightButton setImage:[buttonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

-(void)rightButtonClick{
    
    SsehAddInvoiceTitleViewController * vc = [[SsehAddInvoiceTitleViewController alloc]init];
    TAB_PUSH(self, vc, YES);
}

-(void)creatRefreshHeader{
    
    self.ssehTableView.mj_header = [SsehMJHeaderTool headerWithRefreshingBlock:^{
        pageIndex = 1;
        //请求数据
        //kGetMemberAddress
        NSDictionary * par = @{@"member_id":K_UserDefault_Read(CustomerUserID),
                               @"member_token":K_UserDefault_Read(CustomerUserToken),
                               @"page":[NSNumber numberWithInteger:pageIndex]
                               };
        [[QYNetManager sharedManager]POST:kGetMemberInvoice parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [self.ssehTableView.mj_header endRefreshing];
            NSLog(@"%@",responseObject);
            
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                SsehInvoiceModel * dataModel = [SsehInvoiceModel yy_modelWithDictionary:responseObject];
                [self.dataSource removeAllObjects];
                if (!kArrayIsEmpty(dataModel.data)) {
                    [self.dataSource addObjectsFromArray:dataModel.data];
                    [self.ssehTableView reloadData];
                }
                if (kArrayIsEmpty(self.dataSource)) {
                    self.ssehTableView.emptyTitle = @"暂无数据";
                    self.ssehTableView.emptyImg = @"";
                    self.ssehTableView.showEmpty = YES;
                    
                }else{
                    self.ssehTableView.showEmpty = NO;
                }
            }else{
                [self showErrorTipWithTitle:responseObject[@"error"]];
            }
            
        } Failure:^(NSError *error) {
            [self.ssehTableView.mj_header endRefreshing];
            [self showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
    [self.ssehTableView.mj_header beginRefreshing];
    
}

-(void)creatRefreshAutoNormalFooter{
    self.ssehTableView.mj_footer = [SsehMJFooterTool footerWithRefreshingBlock:^{
        if (kArrayIsEmpty(self.dataSource)) {
            pageIndex = 1;
        }else{
            pageIndex ++;
        }
        NSDictionary * par = @{@"member_id":K_UserDefault_Read(CustomerUserID),
                               @"member_token":K_UserDefault_Read(CustomerUserToken),
                               @"page":[NSString stringWithFormat:@"%d",pageIndex]
                               };
        [[QYNetManager sharedManager]POST:kGetMemberInvoice parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [self.ssehTableView.mj_footer endRefreshing];
            NSLog(@"%@",responseObject);
            
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                SsehInvoiceModel * dataModel = [SsehInvoiceModel yy_modelWithDictionary:responseObject];
                if (!kArrayIsEmpty(dataModel.data)) {
                    [self.dataSource addObjectsFromArray:dataModel.data];
                    [self.ssehTableView reloadData];
                }
                if (kArrayIsEmpty(self.dataSource)) {
                    self.ssehTableView.emptyTitle = @"暂无数据";
                    self.ssehTableView.emptyImg = @"";
                    self.ssehTableView.showEmpty = YES;
                    
                }else{
                    self.ssehTableView.showEmpty = NO;
                }
            }else{
                [self showErrorTipWithTitle:responseObject[@"error"]];
            }
            
        } Failure:^(NSError *error) {
            [self.ssehTableView.mj_header endRefreshing];
            [self showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
}

#pragma mark - tableView

-(UITableView *)ssehTableView{
    
    if (_ssehTableView == nil) {
        
        self.ssehTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT+10, F_DEVICE_W, F_DEVICE_H-TAB_BAR_HEIGHT-HOME_INDICATOR_HEIGHT-10) style:UITableViewStylePlain];
        self.ssehTableView.delegate = self;
        self.ssehTableView.dataSource = self;
        self.ssehTableView.backgroundColor = [UIColor backGroudColorForView];
        self.ssehTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.ssehTableView.showsVerticalScrollIndicator = NO;
        self.ssehTableView.showsHorizontalScrollIndicator = NO;
        [self.ssehTableView registerNib:[UINib nibWithNibName:@"SsehInvoiceTitleTableViewCell" bundle:nil] forCellReuseIdentifier:SsehInvoiceTitleTableViewCellID];
        [self.view addSubview:self.ssehTableView];
        
    }
    return _ssehTableView;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.comeIndex == 1) {
        InvoiceModel *invoideModel = self.dataSource[indexPath.row];
        //类型 1:个人 2:公司
        if ([invoideModel.invoice_type isEqualToString:@"1"]) {
            ChargeInvoicePersionalViewController *personalVC = [[ChargeInvoicePersionalViewController alloc]init];
            personalVC.orderModel = self.orderModel;
            personalVC.invoideModel = invoideModel;
            TAB_PUSH(self,personalVC, YES);
        }else if ([invoideModel.invoice_type isEqualToString:@"2"]) {
            ChargeInvoiceCompanyViewController *companyVC = [[ChargeInvoiceCompanyViewController alloc]init];
            companyVC.orderModel = self.orderModel;
            companyVC.invoideModel = invoideModel;
            TAB_PUSH(self,companyVC, YES);
        }
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SsehInvoiceTitleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SsehInvoiceTitleTableViewCellID];
    
    InvoiceModel * model = self.dataSource[indexPath.row];
    [cell configData:model andIndex:indexPath];
    __weak typeof (self)weakSelf = self;
    cell.editHandle = ^(NSString * _Nonnull typ, NSIndexPath * _Nonnull index) {//编辑
        SsehInvoiceTitleEditViewController * vc = [[SsehInvoiceTitleEditViewController alloc]init];
        vc.invoiceModel = model;
        vc.isPush = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.delHandle = ^(NSString * _Nonnull typ, NSIndexPath * _Nonnull index) {//删除
        [weakSelf delInvoice:index];
    };
    cell.defaultHandle = ^(NSString * _Nonnull typ, NSIndexPath * _Nonnull index) {
        [weakSelf defaultHandleIndex:index];
    };
    
    return cell;
}

-(void)delInvoice:(NSIndexPath *)index{
    
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showLoading];
        InvoiceModel * model = self.dataSource[index.row];
        NSDictionary * par = @{@"member_id":[NSString emptyStr:K_UserDefault_Read(CustomerUserID)],
                               @"member_token":[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)],
                               @"invoice_id":[NSString emptyStr:model.invoice_id]
                               };
        [[QYNetManager sharedManager]POST:kDeleteInvoice parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [self hideLoading];
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                [self.dataSource removeObject:model];
                [self creatRefreshHeader];
            }else{
                [self showErrorTipWithTitle:responseObject[@"error"]];
            }
        } Failure:^(NSError *error) {
            [self hideLoading];
            [self showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定删除该抬头？" preferredStyle:UIAlertControllerStyleAlert];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    
    [self presentViewController:aleVC animated:YES completion:nil];
    
}

-(void)defaultHandleIndex:(NSIndexPath *)index{
    
    //kUpdateDefaultInvoice
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showLoading];
        InvoiceModel * model = self.dataSource[index.row];
        NSDictionary * par = @{@"member_id":[NSString emptyStr:K_UserDefault_Read(CustomerUserID)],
                               @"member_token":[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)],
                               @"invoice_id":[NSString emptyStr:model.invoice_id]
                               };
        [[QYNetManager sharedManager]POST:kUpdateDefaultInvoice parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [self hideLoading];
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                [self creatRefreshHeader];
            }else{
                [self showErrorTipWithTitle:responseObject[@"error"]];
            }
        } Failure:^(NSError *error) {
            [self hideLoading];
            [self showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定将该抬头设置成默认？" preferredStyle:UIAlertControllerStyleAlert];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    
    [self presentViewController:aleVC animated:YES completion:nil];
}

-(NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataSource;
    
}

-(NodataView *)noDataView{
    
    if (_noDataView == nil) {
        _noDataView = [[NodataView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, F_DEVICE_H-NAVIGATION_BAR_HEIGHT)];
        _noDataView.centerImage = [UIImage imageNamed:@"noOrder"];
        _noDataView.titleStr = @"暂无记录";
    }
    return _noDataView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
